import { defineStore } from 'pinia'
import axios from 'axios'

export const useOrdersStore = defineStore('orders', {
  state: () => ({
    orders: [],
    loading: false,
    error: null
  }),
  
  actions: {
    async fetchAllOrders() {
      this.loading = true
      this.error = null
      
      try {
        const response = await axios.get('/getAllOrders')
        this.orders = response.data
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to fetch orders'
        console.error('Error fetching orders:', error)
      } finally {
        this.loading = false
      }
    },
    
    async fetchOrdersByDoctor(dId) {
      this.loading = true
      this.error = null
      
      try {
        const response = await axios.get(`/getOrdersByDoctor/${dId}`)
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to fetch doctor orders'
        console.error('Error fetching doctor orders:', error)
        return []
      } finally {
        this.loading = false
      }
    },
    
    async fetchOrdersByPatient(pId) {
      this.loading = true
      this.error = null
      
      try {
        const response = await axios.get(`/getOrdersByPatient/${pId}`)
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to fetch patient orders'
        console.error('Error fetching patient orders:', error)
        return []
      } finally {
        this.loading = false
      }
    },
    
    async createOrder(order) {
      this.loading = true
      this.error = null
      
      try {
        await axios.post('/insertOrders', order)
        await this.fetchAllOrders()
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to create order'
        console.error('Error creating order:', error)
      } finally {
        this.loading = false
      }
    },
    
    async updateOrder(order) {
      this.loading = true
      this.error = null
      
      try {
        await axios.post('/updateOrders', order)
        await this.fetchAllOrders()
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to update order'
        console.error('Error updating order:', error)
      } finally {
        this.loading = false
      }
    },
    
    async deleteOrder(oId) {
      this.loading = true
      this.error = null
      
      try {
        await axios.get(`/deleteOrders/${oId}`)
        await this.fetchAllOrders()
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to delete order'
        console.error('Error deleting order:', error)
      } finally {
        this.loading = false
      }
    },
    
    // Analytics data for dashboard
    async getOrdersAnalytics() {
      this.loading = true
      this.error = null
      
      try {
        const allOrders = await this.fetchAllOrders()
        
        // Process data for analytics
        const today = new Date().toISOString().split('T')[0]
        const todayOrders = this.orders.filter(order => 
          order.oStart && order.oStart.includes(today)
        )
        
        // Gender distribution
        const genderCount = { male: 0, female: 0 }
        const ageGroups = { '0-18': 0, '19-30': 0, '31-45': 0, '46-60': 0, '60+': 0 }
        const sectionCount = {}
        
        // Process patient data
        for (const order of this.orders) {
          try {
            // Fetch patient details for each order
            const patientResponse = await axios.get(`/getPatientUser/${order.pId}`)
            const patient = patientResponse.data
            
            // Count gender
            if (patient.pGender === 'male' || patient.pGender === '男') {
              genderCount.male++
            } else if (patient.pGender === 'female' || patient.pGender === '女') {
              genderCount.female++
            }
            
            // Count age groups
            const age = patient.pAge || 0
            if (age <= 18) ageGroups['0-18']++
            else if (age <= 30) ageGroups['19-30']++
            else if (age <= 45) ageGroups['31-45']++
            else if (age <= 60) ageGroups['46-60']++
            else ageGroups['60+']++
            
            // Get doctor details to count sections
            const doctorResponse = await axios.get(`/getDoctorUser/${order.dId}`)
            const doctor = doctorResponse.data
            
            // Count by section
            if (doctor.dSection) {
              sectionCount[doctor.dSection] = (sectionCount[doctor.dSection] || 0) + 1
            }
          } catch (error) {
            console.error('Error processing analytics data:', error)
          }
        }
        
        return {
          totalOrders: this.orders.length,
          todayOrders: todayOrders.length,
          genderDistribution: genderCount,
          ageDistribution: ageGroups,
          sectionDistribution: sectionCount
        }
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to generate analytics'
        console.error('Error generating analytics:', error)
        return {}
      } finally {
        this.loading = false
      }
    }
  }
})

// Create an alias export for useOrderStore to maintain compatibility with existing code
export const useOrderStore = useOrdersStore; 